/* 
    绘制矩形范围,截图保存到本地
 */
import VectorSource from "ol/source/Vector";
import Draw, { createBox } from "ol/interaction/Draw";
import { Fill, Stroke, Style } from "ol/style";
export default class screenShot {
	constructor(ol) {
		this.ol = ol;
	}
	drawMap(imgName) {
		const map = this.ol;
		const source = new VectorSource({
			wrapX: false,
		});
		let draw = new Draw({
			source: source,
			type: "Circle",
			style: new Style({
				stroke: new Stroke({
					color: "rgba(195, 59, 83, 1)",
					width: 1,
				}),
				fill: new Fill({
					color: "rgba(195, 59, 83, 0.2)",
				}),
			}),
			geometryFunction: createBox(),
		});
		map.addInteraction(draw);
		draw.on("drawend", (evt) => {
			// source.clear();
			map.removeInteraction(draw);
			console.log(evt);
			map.renderSync();

			let extent = evt.feature.getGeometry().getExtent();
			//地理坐标转换屏幕坐标
			let coord = [extent[0], extent[3]];
			let leftTopPosition = map.getPixelFromCoordinate(coord);
			let coord1 = [extent[2], extent[1]];
			let bottomRightPosition = map.getPixelFromCoordinate(coord1);
			//计算框选矩形的宽度以及高度像素
			let width = Math.abs(bottomRightPosition[0] - leftTopPosition[0]);
			let height = Math.abs(bottomRightPosition[1] - leftTopPosition[1]);
			//计算框选矩形的左上角屏幕坐标
			let minx = leftTopPosition[0];
			let miny = leftTopPosition[1];
			//创建canvas元素
			let mapCanvas =
				document.getElementsByClassName("ol-layer")[0].children[0];
			let image = mapCanvas.getContext("2d");
			image.crossOrigin = "";
			let imageData = image.getImageData(minx, miny, width, height);
			console.log("imageData", imageData);
			let canvas = document.createElement("canvas");
			canvas.crossOrigin = "";
			canvas.width = width;
			canvas.height = height;
			canvas.getContext("2d").putImageData(imageData, 0, 0);
			let dataUrl = canvas.toDataURL(); //转换图片为dataURL
			let link = document.createElement("a");
			link.download = imgName;
			link.href = dataUrl;
			link.click();
			console.log("截图成功");
		});
	}
}
